package com.he.prototypemodel.prorotype;

/**
 * 原型模式，用原型实例指定新创建对象的类型，并且通过拷贝原型来创建新的对象
 * <br/>拷贝对象是直接在内存中进行，理论上比new创建对象性能更高
 */
public class EmpPrototype implements  Cloneable {

    /**
     * 引用类型拷贝，需要引用类型也实现cloneable接口
     */
    private WorkExperience workExperience;
    /**
     * string类型，在拷贝中可以看成基本类型，只拷贝其值
     */
    private String name;
    /**
     * 基本类型（8大基本类型），在拷贝中只拷贝其值
     */
    private int age;

    public EmpPrototype(WorkExperience workExperience, String name, int age) {
        this.workExperience = workExperience;
        this.name = name;
        this.age = age;
    }

    public WorkExperience getWorkExperience() {
        return workExperience;
    }

    public void setWorkExperience(WorkExperience workExperience) {
        this.workExperience = workExperience;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    /**
     * 拷贝方法，对于含有引用对象的原型对象来说，如果只是调用父类默认的clone方法，只是浅拷贝，如果要实现深拷贝
     * 需要在clone方法中重写起拷贝逻辑，为每一个引用类型使用set方法赋予新的引用地址
     * @return
     * @throws CloneNotSupportedException
     */
    @Override
    public Object clone() throws CloneNotSupportedException {
        Object clone = super.clone();
        EmpPrototype emp = (EmpPrototype) clone;
        emp.setWorkExperience((WorkExperience) emp.getWorkExperience().clone());
        return emp;
    }

    @Override
    public String toString() {
        return "Emp{" +
                "workExperience=" + workExperience +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
